package com.example.demo.processor;


import com.example.demo.coder.MessageDecoder;
import com.example.demo.coder.MessageObject;
import com.example.demo.coder.MessageStatus;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Date;

public class Processor {

    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private AttributeKey<String> attributeKey = AttributeKey.valueOf("nickName");

    public void handler(Channel channel,String msg){
        if (msg == null || "".equals(msg)){
            return;
        }
        MessageObject messageObject = MessageDecoder.decoder(msg);
        if (messageObject.getCmd().equals(MessageStatus.LOGIN)){
            channel.attr(attributeKey).set(messageObject.getNickName());
            channels.add(channel);
            for (Channel channel1 : channels){
                MessageObject message = new MessageObject(
                        MessageStatus.SYSTEM,
                        messageObject.getNickName()+"进入聊天室",
                        new Date().getTime(),
                        String.valueOf(channels.size()),
                        messageObject.getNickName()
                        );
                String send = MessageDecoder.encoder(message);
                channel1.writeAndFlush(new TextWebSocketFrame(send));
            }
        }
        if (messageObject.getCmd().equals(MessageStatus.CHAT)){
            for (Channel channel1 : channels){
                MessageObject message = new MessageObject(
                        MessageStatus.CHAT,
                        messageObject.getContent(),
                        new Date().getTime(),
                        String.valueOf(channels.size()),
                        channel != channel1?channel.attr(attributeKey).get():"SELF"
                );
                String send = MessageDecoder.encoder(message);
                channel1.writeAndFlush(new TextWebSocketFrame(send));
            }
        }
        System.out.println("当前在线人数：" + channels.size());
    }

    public void loginOut(Channel channel){
        channels.remove(channel);
        String nickName = channel.attr(attributeKey).get();
        for (Channel channel1 : channels){
                MessageObject message = new MessageObject(
                        MessageStatus.SYSTEM,
                        nickName+"离开了聊天室",
                        new Date().getTime(),
                        String.valueOf(channels.size()),
                        nickName
                );
                String send = MessageDecoder.encoder(message);
                channel1.writeAndFlush(new TextWebSocketFrame(send));
        }
        System.out.println("当前在线人数：" + channels.size());
    }

}
